package com.xiaoyu.tool.filter;

import com.xiaoyu.tool.controller.admin.AdminBaseController;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
 * 登录拦截器
 * */
@Component
public class AdminLoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpSession session = httpServletRequest.getSession();
        Long adminUserId = (Long) session.getAttribute(AdminBaseController.ADMIN_SESSION_ID);
        String url = httpServletRequest.getRequestURI();
        if (url.startsWith("/wx_ali/admin/login")) {
            if (adminUserId != null) {
                HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(httpServletResponse);
                wrapper.sendRedirect("/wx_ali/admin/welcome");
            } else {
                chain.doFilter(httpServletRequest, httpServletResponse);
                return;
            }
        }
        if (adminUserId == null) {
            HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(httpServletResponse);
            wrapper.sendRedirect("/wx_ali/admin/login");
        } else {
            chain.doFilter(httpServletRequest, httpServletResponse);
        }

    }

    @Override
    public void destroy() {

    }
}
